import React, { useEffect, useMemo, useRef, useState } from "react";
import { Input, Form, Space, Button, ColorPicker } from "antd";
import { useTranslation } from "react-i18next";
import { ItagType } from "@/types/type";
import type { ColorPickerProps, GetProp } from "antd";
type Color = Extract<GetProp<ColorPickerProps, "value">, string | { cleared: any }>;

interface Props {
  dialog: string;
  tagdata: ItagType | undefined;
  handletagform: (values: any, color: Color) => void;
  open: boolean;
}

const MyTagForm: React.FC<Props> = ({ dialog, tagdata, handletagform, open }) => {
  const { t } = useTranslation();
  const [color, setColor] = useState<Color>("#1677ff");
  const [nameButton, setNameButton] = useState<string>("");
  const formref = useRef(null);
  const [form] = Form.useForm();

  useEffect(() => {
    if (formref) {
      form.setFieldsValue(tagdata === undefined ? { name: "" } : tagdata);
    }
    setColor(tagdata === undefined ? "#1677ff" : tagdata?.color);
    setNameButton(tagdata === undefined ? "" : tagdata?.name);
  }, [dialog, tagdata]);

  useEffect(() => {
    if (dialog === "AddTag") {
      setNameButton("");
      return;
    }
  }, [open]);

  const bgColor = useMemo<string>(
    () => (typeof color === "string" ? color : color!.toHexString()),
    [color]
  );

  const btnStyle: React.CSSProperties = {
    backgroundColor: bgColor,
  };

  return (
    <Form
      labelCol={{ span: 3 }}
      form={form}
      ref={formref}
      onFinish={(values) => {
        handletagform(values, color);
        form.resetFields();
      }}
      style={{ paddingTop: 16 }}
    >
      {/* 标签名称 */}
      <Form.Item
        label={t("table.name")}
        name="name"
        rules={[{ required: true, message: t("form.nametip") }]}
      >
        <Input
          placeholder={t("form.tagp2")}
          onChange={(e) => setNameButton(e.target.value)}
        />
      </Form.Item>

      {/* 标签颜色 */}
      <Form.Item label={t("color")} name="color" initialValue="#389E0D">
        <ColorPicker
          value={color}
          disabledAlpha={true}
          onChange={(value) => {
            setColor(value.toHexString());
          }}
        >
          <Button type="primary" style={btnStyle}>
            {nameButton}
          </Button>
        </ColorPicker>
      </Form.Item>

      {/* 取消和确认 */}
      <Form.Item style={{ display: "flex", justifyContent: "flex-end" }}>
        <Space size={"middle"}>
          {/* 取消按钮 */}
          <Button onClick={close}>{t("cancel")}</Button>
          {/* 确定按钮 */}
          <Button type="primary" htmlType="submit">
            {t("confirm")}
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default MyTagForm;
